import { IQueryData, IUserAnswer } from '../typings';

/**
 * 生成一个组装后的userAnswer对象
 * 根据点击选项里的answer比对查询列表queryList是否包含正确答案返回答案信息
 * @param queryList 查询state.queryList列表
 * @param id 当前题目的 curQuestion.id
 * @param answer 点击选项里的answer(data-answer="4")
 * @returns userAnswer 返回答案信息(无论正确或错误)
 */
function formatUserAnswer(
  queryList: IQueryData[],
  id: string,
  answer: string
): IUserAnswer {
  let userAnswer: IUserAnswer = {
    qid: '0',
    question: '',
    url: '',
    explains: '',
    userAnswer: '',
    rightAnswer: '',
    isRight: false
  };

  //用any的原因是 ts本身不支持字符串拼接的属性类型推断的校验
  //所以只能用any, 下面item[`item${item.answer}`]才不会出现类型错误
  queryList.map((item: any) => {
    if (item.id === id) {
      userAnswer.qid = item.id;
      userAnswer.question = item.question;
      userAnswer.url = item.url;
      userAnswer.explains = item.explains;
      userAnswer.userAnswer = item[`item${answer}`];
      userAnswer.rightAnswer = item[`item${item.answer}`];
      userAnswer.isRight = item.answer === answer ? true : false;
    }
    return item;
  });

  return userAnswer;
}

export { formatUserAnswer };
